﻿using NetDh.Lib;
using NetDh.Lib.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace NetDh.Presentation.Common
{
    /*此类无用，这里捕获的异常，没有包含404等非内部代码异常。因此mvc异常处理移到Global.asax.cs的Application_Error中。*/

    public class MvcExceptionFilterAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            var httpContext = filterContext.RequestContext.HttpContext;
            StringBuilder sb = new StringBuilder();
            //TestBusinessException 业务自定义异常示例
            if (filterContext.Exception is TestBusinessException)
            {
                sb.AppendLine("【TestBusinessException】");//比如，特殊异常增加特殊标识
                //var ex = (TestBusinessException)actionExecutedContext.Exception;//是否需要使用，没使用则注释
            }
            sb.AppendLine(DateTime.Now.ToStringX() + " ---mvc");
            sb.AppendLine(filterContext.Exception.GetAllErrorMsg());
            var method = httpContext.Request.HttpMethod.ToUpper();
            //X-Requested-With不为null时，说明是ajax的get请求。 如果是局部页面的ajax get请求，也是走此流程。
            if (method == "POST" || (method == "GET" && httpContext.Request.Headers["X-Requested-With"] != null))
            {
                filterContext.Result = new ContentResult { Content = sb.ToString() };
            }
            else
            {
                //filterContext.Result = new RedirectResult("/error") ;
                filterContext.Result = new ViewResult() { ViewName = "Error" };
            }
            //异常处理结束后,一定要将ExceptionHandled设置为true,否则仍然会继续抛出错误。
            filterContext.ExceptionHandled = true;
            //记录日志时，详细记录当时的uri和header
            sb.AppendLine("【Uri】:" + httpContext.Request.Url);
            sb.AppendLine("【Header】:" + httpContext.Request.Headers);
            MemoryLog.Add(sb.ToString(), MemoryLogType.error);
        }
    }
}
